/**
 * 获取积木报表打印地址
 * @param {Array} list   需要转换的数据
 * @param {String} protectValue   保护间隔
 * @param {String} type  子带类型  up上行、down下行
 * @returns {Array}
 */
export function transformSubBandList(list, protectValue, type, isCopy) {
  if (type === 'up') {
    list = list.map(item => {
      if (item.exchangeRelationList.length) {
        if (item.exchangeRelationList.every(r => r.isCopy === 1)) {
          // const tempExchangeRelationList = JSON.parse(JSON.stringify(item.exchangeRelationList))
          //   item.exchangeRelationList = tempExchangeRelationList  
        } else if (item.exchangeRelationList.some(r => r.isCopy === 1)) {
          const copyRelationList = item.exchangeRelationList.filter(i => i.isCopy === 1)
          let ids = []
          copyRelationList.forEach(i => ids.push(i.mergeId))
          let s1 = new Set(ids)
          item.copyMergeId = [...s1]

          const num = item.exchangeRelationList.length

          const tempExchangeRelationList = JSON.parse(JSON.stringify(item.exchangeRelationList))
          
          item.exchangeRelationList = tempExchangeRelationList.filter(i => i.isCopy === 0)
          item.copyNum = num / item.exchangeRelationList.length

          const copyExchangeRelationList = tempExchangeRelationList.filter(i => i.isCopy === 1)
          if (copyExchangeRelationList.length) {
            const stepNum = item.exchangeRelationList.length
            let otherProp = JSON.parse(JSON.stringify(item))
            delete otherProp.exchangeRelationList
            item.copyExchangeRelationList = chunk(otherProp, copyExchangeRelationList, stepNum)
          }
        } else if (isCopy) {
          const tempExchangeRelationList = JSON.parse(JSON.stringify(item.exchangeRelationList))
          if (item.exchangeRelationList.every(everyItem => !everyItem.id)) {
            item.exchangeRelationList = tempExchangeRelationList
          } else {
            item.exchangeRelationList = tempExchangeRelationList.filter(i => i.isCopy === 0)
          }
        }
      }
      return item
    })
  }
  list = list.map(item => {
    item.allCopy = item.exchangeRelationList.every(everyItem => everyItem.isCopy !== 1)
    return {
      ...item,
      subNameFlag: false,
      subUserFlag: false,
      subRelationFlag: false
    }
  })
  if (!list.length) return []
  const _type = type === 'up' ? 'down' : 'up'
  // list = mergeSandList(list, type)arrowMark
  list[list.length - 1].arrowMark = true
  list[0].leftArrowMark = true
  
  list = render(list, protectValue, type, _type)

  list = list.map(listItem => {
    if (listItem.copyExchangeRelationList && listItem.copyExchangeRelationList.length) {
      listItem.copyExchangeRelationList = render(listItem.copyExchangeRelationList, protectValue, type, _type)
    }
    return listItem
  })

  return list
}


function render(list, protectValue, type, _type) {
  return list.map(item => {
    if (!item.exchangeRelationList.length) {
      item.render = [
        { type: 'guard', width: protectValue / item.bandWidth * 100 },
        { type: 'empty' },
        { type: 'guard', width: protectValue / item.bandWidth * 100 }
      ]
    } else {
      item.exchangeRelationList = transformRelationList(item.exchangeRelationList, type, _type)
      if (item.exchangeRelationList.length === 1) {
        const relationItem = item.exchangeRelationList[0]
        const left = relationItem.BandProtectStartFrenquency
        const content = relationItem.BandRequestBandWidth
        const right = relationItem.BandProtectEndFrenquency
        const bandWidth = item.bandWidth
        // 用户带宽 = 子带带宽
        if (relationItem.BandRequestBandWidth === item.bandWidth) {
          item.render = [
            { 
              type: 'relation',
              width: content / bandWidth * 100,
              ...relationItem,
              subNameFlag: item.subNameFlag,
              subUserFlag: item.subUserFlag,
              subRelationFlag: item.subRelationFlag
            },
          ]
        // 子带的开始频率 等于 子带用户的开始频率
        } else if (relationItem.BandStartFrenquency === item.startFrenquency) {
          item.render = [
            { 
              type: 'relation',
              width: content / bandWidth * 100,
              ...relationItem,
              subNameFlag: item.subNameFlag,
              subUserFlag: item.subUserFlag,
              subRelationFlag: item.subRelationFlag
            },
            { type: 'guard', width: left / item.bandWidth * 100 },
            { type: 'empty' },
            { type: 'guard', width: right / item.bandWidth * 100 },
          ]
        // 子带用户信息，末尾的保护间隔为 0 时
        } else if (relationItem.BandProtectEndFrenquency === 0) {
          // 子带开始频率 + 用户带宽 = 子带结束频率
          if ((relationItem.BandStartFrenquency + relationItem.BandRequestBandWidth) === item.endFrequency) {
            item.render = [
              { type: 'guard', width: left / item.bandWidth * 100 },
              { type: 'empty' },
              { 
                type: 'relation',
                width: content / bandWidth * 100,
                ...relationItem,
                subNameFlag: item.subNameFlag,
                subUserFlag: item.subUserFlag,
                subRelationFlag: item.subRelationFlag
              },
            ]
          // 子带开始频率 + 用户带宽 ≠ 子带结束频率 
          } else {
            const afterWidthTemp = item.endFrequency - relationItem.BandStartFrenquency - relationItem.BandRequestBandWidth
            const afterEmpty = (afterWidthTemp > protectValue) ? (afterWidthTemp - protectValue) : 0
            const afterGuard = (afterWidthTemp > protectValue) ? protectValue : afterWidthTemp
            item.render = [
              { type: 'guard', width: left / item.bandWidth * 100 },
              { type: 'empty' },
              { 
                type: 'relation',
                width: content / bandWidth * 100,
                ...relationItem,
                subNameFlag: item.subNameFlag,
                subUserFlag: item.subUserFlag,
                subRelationFlag: item.subRelationFlag
              },
              { type: 'empty', width: afterEmpty / item.bandWidth * 100 },
              { type: 'guard', width: afterGuard / item.bandWidth * 100 },
            ]
          }
        // 子带用户信息，开始的保护间隔为 0 时
        } else if (relationItem.BandProtectStartFrenquency === 0) {
          // 用户开始频率 = 子带开始频率
          if (relationItem.BandStartFrenquency === item.startFrenquency) {
            // const beforeWidthTemp = item.endFrequency - relationItem.BandStartFrenquency - relationItem.BandRequestBandWidth
            const beforeEmpty = (left > protectValue) ? 0 : (protectValue - left)
            const afterEmpty = ((item.bandWidth - left) > protectValue) ? protectValue : (item.bandWidth - left - protectValue)
            item.render = [
              { 
                type: 'relation',
                width: content / item.bandWidth * 100,
                ...relationItem,
                subNameFlag: item.subNameFlag,
                subUserFlag: item.subUserFlag,
                subRelationFlag: item.subRelationFlag
              },
              { type: 'guard', width: beforeEmpty / item.bandWidth * 100 },
              { type: 'empty' },
              { type: 'guard', width: afterEmpty / item.bandWidth * 100 },
            ]
          // 用户开始频率 ≠ 子带开始频率 
          } else {
            const afterWidthTemp = item.endFrequency - relationItem.BandStartFrenquency - relationItem.BandRequestBandWidth
            item.render = [
              { type: 'guard', width: protectValue / item.bandWidth * 100 },
              { type: 'empty' },
              { 
                type: 'relation',
                width: content / item.bandWidth * 100,
                ...relationItem,
                subNameFlag: item.subNameFlag,
                subUserFlag: item.subUserFlag,
                subRelationFlag: item.subRelationFlag
              },
              { type: 'empty', width: afterWidthTemp / item.bandWidth * 100 },
              { type: 'guard', width: protectValue / item.bandWidth * 100 },
            ]
          }
        }

        // 其他情况下↓
        if (!item.render) {
          item.render = [
            { type: 'guard', width: left / item.bandWidth * 100 },
            { type: 'empty' },
            { 
              type: 'relation',
              width: content / bandWidth * 100,
              ...relationItem,
              subNameFlag: item.subNameFlag,
              subUserFlag: item.subUserFlag,
              subRelationFlag: item.subRelationFlag
            },
            { type: 'empty', width: (item.endFrequency*10000 - (relationItem.BandStartFrenquency*10000 + relationItem.BandRequestBandWidth*10000 + relationItem.BandProtectEndFrenquency*10000))/10000/item.bandWidth * 100 },
            { type: 'guard', width: right / item.bandWidth * 100 },
          ]
        }
        // 111111111111111111111
      } else {
        console.log('多个子带--多个用户');
        let renderList = item.exchangeRelationList.sort((a, b) => a.BandStartFrenquency - b.BandStartFrenquency)
        item.render = []
        renderList.forEach((renderItem,index) => {
          if (index === 0) {
            if (renderItem.BandStartFrenquency === item.startFrenquency) {
              item.render.push(
                {
                  type: 'relation',
                  width: renderItem.BandRequestBandWidth / item.bandWidth * 100,
                  ...renderItem,
                  UserName: renderItem.BandRequestBandWidth <= protectValue ? '' : renderItem.UserName,
                  [item.upDownDirection === 'up' ? 'downUserName' : 'upUserName']: renderItem.BandRequestBandWidth <= protectValue ? '' : renderItem[item.upDownDirection === 'up' ? 'downUserName' : 'upUserName'],
                  subNameFlag: item.subNameFlag,
                  subUserFlag: item.subUserFlag,
                  subRelationFlag: item.subRelationFlag
                },
                {
                  type: 'guard',
                  width: renderItem.BandProtectStartFrenquency / item.bandWidth * 100
                }
              )
            } else {
              item.render.push(
                { type: 'guard', width: renderItem.BandProtectStartFrenquency / item.bandWidth * 100 },
                { type: 'empty', width: (renderItem.BandStartFrenquency - item.startFrenquency - renderItem.BandProtectStartFrenquency) / item.bandWidth * 100 },
                {
                  type: 'relation',
                  width: renderItem.BandRequestBandWidth / item.bandWidth * 100,
                  ...renderItem,
                  UserName: renderItem.BandRequestBandWidth <= protectValue ? '' : renderItem.UserName,
                  [item.upDownDirection === 'up' ? 'downUserName' : 'upUserName']: renderItem.BandRequestBandWidth <= protectValue ? '' : renderItem[item.upDownDirection === 'up' ? 'downUserName' : 'upUserName'],
                  subNameFlag: item.subNameFlag,
                  subUserFlag: item.subUserFlag,
                  subRelationFlag: item.subRelationFlag
                },
              )
            }
          } else {
            if ((renderItem.BandStartFrenquency + renderItem.BandRequestBandWidth) === item.endFrequency) {
              item.render.push(
                { type: 'empty' },
                {
                  type: 'relation',
                  width: renderItem.BandRequestBandWidth / item.bandWidth * 100,
                  ...renderItem,
                  UserName: renderItem.BandRequestBandWidth <= protectValue ? '' : renderItem.UserName,
                  [item.upDownDirection === 'up' ? 'downUserName' : 'upUserName']: renderItem.BandRequestBandWidth <= protectValue ? '' : renderItem[item.upDownDirection === 'up' ? 'downUserName' : 'upUserName'],
                  subNameFlag: item.subNameFlag,
                  subUserFlag: item.subUserFlag,
                  subRelationFlag: item.subRelationFlag
                },
              )
            } else {
              item.render.push(
                { type: 'empty' },
                {
                  type: 'relation',
                  width: renderItem.BandRequestBandWidth / item.bandWidth * 100,
                  ...renderItem,
                  UserName: renderItem.BandRequestBandWidth <= protectValue ? '' : renderItem.UserName,
                  [item.upDownDirection === 'up' ? 'downUserName' : 'upUserName']: renderItem.BandRequestBandWidth <= protectValue ? '' : renderItem[item.upDownDirection === 'up' ? 'downUserName' : 'upUserName'],
                  subNameFlag: item.subNameFlag,
                  subUserFlag: item.subUserFlag,
                  subRelationFlag: item.subRelationFlag
                },
                { type: 'empty', width: (item.endFrequency - renderItem.BandStartFrenquency - renderItem.BandRequestBandWidth - renderItem.BandProtectEndFrenquency)  / item.bandWidth * 100 },
                { type: 'guard', width: renderItem.BandProtectEndFrenquency / item.bandWidth * 100 },
              )
            }
          }
        })
      }
    }
    return item
  })
}


/**
 * 判断合理区间
 * @param {Array} data  数据轴: [ [1, 6], [10, 50], [200, 250] ]
 * @param {Array} target  目标区间:[50, 120]
 * @returns {Bolean}
 */
export function judgeReasonable(data, target) {
  // 判断数据的合理性
  if (!(Array.isArray(target) && Array.isArray(data))) return
  if (!target.length) return
  if (target[0] > target[target.legnth - 1]) return
  // 判断是否超过边界值
  if (target[0] < Math.min(...data[0]) || target[1] > Math.max(...data[data.length - 1])) {
    console.log('超过边界值-------------')
    return true
  }
  // 判断是否重叠
  for (let i = 0; i < data.length; i++) {
    const element = data[i]
    if (Math.max(...element) > Math.min(...target) && Math.min(...element) < Math.max(...target)) {
      console.log('重叠了-------------')
      return true
    } else {
      console.log('未重叠--------------')
    }
  }
  return false
}


function chunk(item, array, size=0){
	//获取数组的长度，如果你传入的不是数组，那么获取到的就是undefined
    var length = array.length;
    //判断不是数组，或者size没有设置，size小于1，就返回空数组
    if (!length || !size || size < 1) {
    	return []
    };
	var index = 0 //用来表示切割元素的范围start
	var resIndex = 0 //用来递增表示输出数组的下标
	//根据length和size算出输出数组的长度，并且创建它。
	var num = Math.ceil(length / size);
	var obj = new Array(num);
	//进行循环
	while (index < length) {
		//循环过程中设置result[0]和result[1]的值。该值根据array.slice切割得到。
    obj[resIndex++] = {
      ...item,
      exchangeRelationList: array.slice(index, (index += size))
    };  
	};
  return obj
}

/**
 * 对transformSubBandList函数中的 item.exchangeRelationList 进行处理
 * @param {Array} list  
 * @param {String} type 
 * @param {String} _type 
 * @returns {Array}
 */
function transformRelationList(list, type, _type) {
  list.forEach(relation => {
    for (const key in relation) {
      if (key.indexOf(_type) !== -1) {
        // delete relation[key]
      } else if (key.indexOf(type) !== -1 && key !== 'updateBy' && key !== 'updateTime' ) {
        relation[key.replace(type, '')] = relation[key]
        // delete relation[key]
      }
    }
  })
  return list
}

/**
 * 根据目标id，和长度length，查找的目标id后的数据长度的id集合
 * @param {Array} list 查找的数组
 * @param {String} targetId  查找的目标id
 * @param {String} length  查找的目标id后的数据长度
 * @returns {Array} 查找的目标id后的数据长度的id集合
 */
export function getSubBandIds(list, targetId, length) {
  const ids = []
  let flag = false
  for (let i = 0; i < list.length; i++) {
    const e = list[i]
    if (ids.length >= length) break
    if (flag) ids.push(e)
    if (e.id === targetId) flag = true
  }
  return ids
}

/**
 * 根据提供的数组，按照指定的长度（num），转换成[{value: 0, name: '子带1-12'}，{value: 1, name: '子带13-24'}...]
 * @param {Array} arr 目标数组
 * @param {Number} num 指定的长度
 * @returns {Array} 下拉框数据集合
 */
export function chunkArrayByNum(arr, num) {
  let j = 0,
      o = j;
  let newArray = [];
  while (j < arr.length) {
      j += num;
      newArray.push([arr.slice(o, j)]);
      o = j;
  }
  // return newArray;
  return newArray.map((item, index) => {
    const target = item[0]
    return { value: index, name: `子带${target[0].waveBeamNo}-${target[target.length - 1].waveBeamNo}`, id: `up_${target[0].id}` }
  })
}

/**
 * 自动计算字体大小
 * @param {String} size 字号
 * @param {String} text 文字
 * @param {*} w 
 * @returns {String} size 字号
 */
export function autoFontSize(size,text,w){
    const text_length = text.length //获取文字长度
    const dv = w-(text_length*size) //判断是否超过容器
  if (dv<=0) {
    //||size 是防止为0的时候显示错误
    //  -20 是为了两边留点距离
    return ((w-20)/text_length) || size  
  }else{
    return size //不超过容器宽度就默认大小
  }
}

